package message.preset;

import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.function.Consumer;

import message.AbstractMessageBuilder;
import message.reflect.HandlerMapper;

public class StringMessageBuilder extends AbstractMessageBuilder{
	
	public StringMessageBuilder(Consumer<? super Object> callback, HandlerMapper mapper) {
		super(callback);
		this.charset = mapper.getCharset();
	}

	private Charset charset;
	private int step = 0;
	private int i = 0;
	private int len;
	private byte[] bs;
	
	@Override
	public boolean read(ByteBuffer byteBuffer) {
		switch(step){
		case 0:
			try {
				len = byteBuffer.getInt();
			} catch (BufferUnderflowException e) {
				return false;
			}
			bs = new byte[len];
			step++;
		case 1:
			while(i < len) {
				try {
					bs[i] = byteBuffer.get();
				} catch (BufferUnderflowException e) {
					return false;
				}
				i++;
			}
			this.build = new String(bs, charset);
			step++;
		}
		return super.read(byteBuffer);
	}
	
}
